package com.liukaixin.product.ru.util;

import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AlertDialog;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liukaixin.product.ru.AppController;
import com.liukaixin.product.ru.data.model.User;
import com.liukaixin.product.ru.enumerate.BusinessExceptionEnum;
import com.orhanobut.logger.Logger;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 以异常为逻辑控制的检查工具类.
 *
 * Created by liukaixin on 16/9/1.
 */

public class CheckUtil {

    /**
     * 检查用户名和密码输入是否规范.1:用户名为空 2:密码为空 3:用户名为不正确的邮箱
     *
     * @param email 用户名(邮箱)
     */
    public static void checkValidMail(String email) {
        if (!isCorrectEmail(email)) {
            throw new BusinessException(BusinessExceptionEnum.INVALID_EMAIL.getDescription());
        }
    }

    /**
     * 判断邮箱号是否合法.
     *
     * @param email 邮箱
     * @return 是否合法
     */
    public static boolean isCorrectEmail(String email){
        String str="^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*" +
                "@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    /**
     * 判断一个字符串是否是数字和字母的组合且长度为8到16位.
     *
     * @param string 字符串
     * @return
     */
    public static boolean isAAndDBetween8to16(String string) {
        String regex = "^(\\\\d+[A-Za-z]+[A-Za-z0-9]*)|([A-Za-z]+\\\\d+[A-Za-z0-9]*)$";
        Pattern p = Pattern.compile(string);
        Matcher m = p.matcher(regex);
        return true;
    }

    /**
     * 判断是否有网络.
     *
     * @param context 上下文
     * @return
     */
    public static boolean haveNetWork(Context context) {
        ConnectivityManager connectivityManager =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info == null || !info.isAvailable()) {
            new AlertDialog.Builder(context)
                    .setTitle("提醒：")
                    .setMessage("抱歉，目前无法连接网络。\n请检查您的手机网络连接！")
                    .setPositiveButton("打开网络设置", (dialog, which) -> {
                        Intent intent = null;
                        //判断手机系统的版本  即API大于10 就是3.0或以上版本
                        if (android.os.Build.VERSION.SDK_INT > 10) {
                            intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                        } else {
                            intent = new Intent();
                            ComponentName component =
                                    new ComponentName("com.android.settings",
                                            "com.android.settings.WirelessSettings");
                            intent.setComponent(component);
                            intent.setAction("android.intent.action.VIEW");
                        }
                        context.startActivity(intent);
                    })
                    .setNegativeButton("朕知道了!", null)
                    .show();
            return false;
        } else {
            return true;
        }
    }

    public static void validVerificationCode(String verificationCode) {
        if (verificationCode == null || "".equals(verificationCode)) {
            throw new BusinessException(BusinessExceptionEnum.EMPTY_VERIFICATION.getDescription());
        }
    }

    /**
     * 检查输入为空.
     *
     * @param name
     * @param input
     */
    public static void checkEmptyInput(String name, String input) {
        if (input == null || "".equals(input)) {
            throw new BusinessException(name + BusinessExceptionEnum.CANNOT_BE_EMPTY.getDescription());
        }
    }

    /**
     * 判断是否登录,登录则返回user
     *
     * @return
     */
    public static User isLogin() {
        ACache aCache = AppController.getInstance().getCache();
        String data = aCache.getAsString("user");
        if (data == null || data.equals("")) {
            return null;
        }
        return JSON.parseObject(data, User.class);
    }
}
